<?php

declare(strict_types=1);

namespace App\Job;

use _PHPStan_adbc35a1c\Nette\Neon\Exception;
use App\Model\Applet;
use App\Model\AppletPlayletRel;
use App\Model\Playlet;
use App\Model\PlayletEpisodes;
use App\Model\PlayletTag;
use GuzzleHttp\Client;
use Hyperf\AsyncQueue\Job;
use Psr\Log\LoggerInterface;
use Hyperf\Utils\ApplicationContext;
use Hyperf\Logger\LoggerFactory;
use function PHPUnit\Framework\exactly;

class DyEmpowerJob extends Job
{

    public $playet_id;

    public $applet_id;
    protected LoggerInterface $logger;

    //获取token
    public static $getTokenUrl = "https://open.douyin.com/oauth/client_token/";
    //授权小程序
    public static $authorizeUrl = "https://open.douyin.com/api/playlet/v2/auth/authorize/";
    //剧目绑定
    public static $dramaBindUrl = "https://open.douyin.com/api/playlet/v2/album/bind/";
    public function __construct(array $playet_id,array $applet_ids)
    {
        $container = ApplicationContext::getContainer();
        $this->logger = $container->get(LoggerFactory::class)->get('log', 'dyrevod');
        $this->playet_ids = $playet_id;
        $this->applet_ids = $applet_ids;
    }

    public function handle()
    {
        try {
            $this->logger->info('开始上传提审剧目');
            $this->logger->info('查询短剧是否存在',[$this->playet_ids]);
//            return;
            //获取短剧ID
            $playletData = Playlet::query()->whereIn('id', $this->playet_ids)->where('album_id','!=',0)->get();

            if($playletData->isNotEmpty()){

                $appletData = Applet::query()->where(['id' => 20000])->first();
                $appletInfo = Applet::query()->whereIn('id',$this->applet_ids)->pluck('app_id')->toArray();

                foreach ($playletData as $playletDatum){
                    $playlet_name = $playletDatum->name;
                    $album_id = $playletDatum->album_id;
                    $this->logger->info('短剧ID',[$album_id]);

                    if(!empty($appletData)) {
                        $this->logger->info('需要授权的小程序',[$this->applet_ids]);
                        $this->logger->info('授权的短剧',[$playlet_name]);
                        //获取token
                        $accessToken = $this->getDyAccessToken($appletData->id,$appletData->app_id,$appletData->app_secret);
                        $this->logger->info('授权的短剧token',[$accessToken]);
                        $this->logger->info('授权的短剧token',[$appletData->id]);
                        $this->logger->info('授权的短剧token',[$appletData->app_id]);
                        $this->logger->info('授权的短剧token',[$appletData->app_secret]);
                        if(!empty($accessToken)){
                            //统计短剧剧集总数
                            $episode_list = PlayletEpisodes::query()->where(['playlet_id' => $playletDatum->id,'is_dy_upload' => 3])
                                ->where('dy_cloud_id','!=',0)
                                ->where('open_video_id','!=',0)
                                ->orderBy('playlet_number','asc')
                                ->select(['id','dy_cloud_id','dy_episodes_id','open_video_id','playlet_number_name','playlet_number'])->get();
                            if(!empty($episode_list)){
                                foreach ($episode_list as $item){
                                    $this->logger->info('集数',[$item->playlet_number]);
                                    //绑定页面
                                    $this->dramaBind($accessToken,$album_id,$item->dy_episodes_id,$playletDatum->id,$item->playlet_number,$appletInfo);
                                }
                                //授权小程序
                                $this->authorize($album_id,$accessToken,$appletData->app_id,$appletInfo);

                            }else{
                                $this->logger->error('不存在集数');
                            }
                        }else{
                            $this->logger->error('短剧:'.$playlet_name.' 没有对应的token');
                        }

                    }else{
                        $this->logger->error('小程序不存在',[$this->applet_id]);
                    }

                }











            }else{
                $this->logger->error('短剧不存在',[$this->playet_id]);
            }
        }catch (\Exception $e){
            $playletData->save();
            $this->logger->error('请求抖音提交审核剧目接口|错误：' . $e->getLine() . '|' . $e->getMessage());
        }
    }

    public function authorize($album_id,$accessToken,$app_id,$appletInfo){

        $params         = [
            "ma_app_id"   =>$app_id,
            "album_id"   => $album_id,
            "app_id_list"   => $appletInfo,
            "increment" => true,
        ];
        $taskUrl = self::$authorizeUrl;
        $this->logger->info('请求剧目授权信息数据：'.PHP_EOL.var_export(['result' => $params], true));
        $this->logger->info('请求剧目授权信息Url：'.$taskUrl);
        $postResult  = $this->request($params, $taskUrl,'POST',$accessToken);
        if($postResult['err_no'] == 0){
            $this->logger->info('调用剧目授权信息接口成功 返回数据：'.PHP_EOL.var_export(['result' => $postResult], true));
            return $postResult;
        }else{
            $this->logger->error('调用剧目授权信息接口失败 返回数据：'.PHP_EOL.var_export(['result' => $postResult], true));
        }
        return false;
    }


    public function dramaBind($accessToken,$album_id,$episode_id,$playlet_id,$playlet_number,$appletInfo){
        try {
            sleep(1);

            foreach ($appletInfo as $applet){


                $params = [
                    'schema_bind_type' => 1,
                    'app_id' => $applet,
                    "single_schema_bind" => [
                        'album_id'=>$album_id,
                        "episode_id" => $episode_id,
                        "path" => "pages/videopage/videopage",
                        "params" => [
                            ["key" => "pid", "value" => (string)$playlet_id],
                            ["key" => "peid", "value" => (string)$playlet_number],
                            ["key" => "dt", "value" => (string)time()] //无用的参数
                        ]
                    ]
                ];
                $updateUrl = self::$dramaBindUrl;
                $this->logger->info('请求小程序：',[$applet]);
//                $this->logger->info('请求数据：'.PHP_EOL.var_export(['result' => $params], true));
                $this->logger->info('请求Url：'.$updateUrl);
                //开始上传
                //$reviewResult['err_no'] = 0;
                $reviewResult  = $this->request($params, $updateUrl,'POST',$accessToken);
                if($reviewResult['err_no'] == 0){
                    $this->logger->info('短剧绑定页面成功 短剧episode_id：',[$episode_id]);
//                    return $reviewResult;
                }else{
                    $this->logger->error('短剧绑定页面失败 返回数据：'.PHP_EOL.var_export(['result' => $reviewResult], true));
                }
            }
            return true;

        }catch (\Exception $e){
            $this->logger->error('请求抖音|错误：' . $e->getLine() . '|' . $e->getMessage());
            return $this->dramaBind($accessToken,$album_id,$episode_id,$playlet_id,$playlet_number,$appletInfo);
        }
    }
    public function getDyAccessToken($applet_id,$app_id,$app_secret){

        $container = ApplicationContext::getContainer();

        $redis = $container->get(\Hyperf\Redis\RedisFactory::class)->get('dy');

        $key = 'dy_admin_access_token';
        $key .= $applet_id;
        $accessToken = $redis->get($key);
//        if(empty($accessToken)){
            $params         = [
                'grant_type' => 'client_credential',
                'client_key'    => $app_id,
                'client_secret'   => $app_secret
            ];
            //获取token
            $accessTokenInfo     = $this->request($params, self::$getTokenUrl,'POST');
            if (!empty($accessTokenInfo['data']['access_token'])){
                $accessToken = $accessTokenInfo['data']['access_token'];
                $redis->setex($key,7100,$accessToken);
            }else{
                $accessToken = "";
            }
//        }
        $this->logger->info('抖音token为：'.$accessToken);
        return $accessToken;
    }

    /**
     * 传入数组进行HTTP POST请求
     */
    function request(array $params, string $url,string $method,string $access_token = null)
    {
        $client   = new Client([
            'timeout' => 3
        ]);
        $headers       = ['Content-Type' => 'application/json'];
        if(!empty($access_token)){
            $headers['access-token'] = $access_token;
        }

        $requestParams = [
            'headers' => $headers,
        ];
        if ($method == 'GET') {
            $requestParams['query'] = $params;
        } else {
            $requestParams['json'] = $params;//json_encode($params,JSON_UNESCAPED_UNICODE);
        }
        $response = $client->request($method,$url, $requestParams);
        if ($response->getStatusCode() !== 200) {
            return '';
        }
        $result   = $response->getBody()->getContents();
        $resultArr = json_decode($result,true);
        return $resultArr;

    }
}